package ibm.cognos.imt;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Properties;

/**
 * Created with IntelliJ IDEA.
 * User: eric
 * Date: 3/14/14
 * Time: 2:02 PM
 * To change this template use File | Settings | File Templates.
 */
public class BiServerConfig {

    private static Properties config = new Properties();
    static {
        try {
            URI uri = BiServerConfig.class.getResource(".").toURI();
            String biserverConfigFile = getBiServerConfigFilePath(uri);
            System.out.println("Load server configuration from "+biserverConfigFile);
            config.load(new FileInputStream(new File(biserverConfigFile)));
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String getBiServerConfigFilePath(URI uri) {

        File file = new File(uri.getPath()+"/conf/BIServer.properties");
        while(!file.exists()) {
            uri = parent(uri);
            file = new File(uri.getPath() + "/conf/BIServer.properties");
        }
        return file.getAbsolutePath();
    }

    private static URI parent(URI uri) {
        return uri.getPath().endsWith("/") ? uri.resolve("..") : uri.resolve(".");
    }


    public static void main(String[] args) {
        System.out.println(BiServerConfig.dispatcherURI());
    }

    public static String dispatcherURI() {
        return "http://" + config.getProperty("BiServerIP") + ":" + config.getProperty("dispatcherPort") + config.getProperty("dispatcherServlet");
    }

    public static String gatewayCgi() {
        return gatewayResourceURI()+config.getProperty("gatewayCgi");
    }

    public static String gatewayPort() {
        return config.getProperty("gatewayPort");
    }

    public static String gatewayResourceURI() {
        return "http://" + config.getProperty("BiServerIP") + ":" + config.getProperty("gatewayPort") + config.getProperty("gatewayResourceUri");
    }

}
